/**
 * 客户端测试1207接口脚本
 * 专注于测试：角色训练功能、训练经验计算、升级逻辑
 */

const http = require('http');
const WebSocket = require('ws');

// 测试配置
const CONFIG = {
    server: {
        host: '127.0.0.1',
        port: 3000,
        protocol: 'http'
    },
    testUser: {
        mobile: '17091271111',
        password: '123456',
        passwordHash: 'e10adc3949ba59abbe56e057f20f883e'
    },
    testCharacter: {
        name: '测试角色',
        sex: 1,
        roleType: 1,
        headIndex: 2
    }
};

class Code1207Tester {
    constructor() {
        this.token = null;
        this.userId = null;
        this.ws = null;
        this.characters = [];
        this.selectedCharacter = null;
        this.testResults = [];
        this.trainingResults = [];
        this.characterInfo = null;
    }

    async runTest() {
        console.log('🏋️ 开始客户端1207接口测试...\n');
        console.log('测试目标：HTTP登录 → WebSocket连接 → 选择角色 → 查询角色信息 → 持续训练直到升级\n');

        try {
            await this.testHttpLogin();
            await this.testWebSocketConnection();
            await this.testQueryCharacters();

            if (this.characters.length === 0) {
                await this.testCreateCharacter();
                await this.testQueryCharacters();
            }

            await this.testSelectCharacter();
            await this.testQueryCharacterInfo();
            await this.testContinuousTraining();
            await this.testDisconnect();
            this.printTestResults();
        } catch (error) {
            console.error('❌ 测试过程中发生错误:', error.message);
            this.addTestResult('整体测试', false, error.message);
        }
    }

    async testQueryCharacterInfo() {
        console.log('\n👤 步骤6: 查询角色信息...');
        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            this.addTestResult('查询角色信息', false, 'WebSocket未连接');
            return;
        }

        return new Promise((resolve) => {
            const timeout = setTimeout(() => {
                this.ws.removeListener('message', handler);
                console.log('⚠️ 查询角色信息超时');
                this.addTestResult('查询角色信息', false, '请求超时');
                resolve();
            }, 10000);

            const handler = (raw) => {
                try {
                    const msg = JSON.parse(raw.toString());
                    if (msg && (msg.act_id === 1000 || msg.act_id === 300)) {
                        clearTimeout(timeout);
                        this.ws.removeListener('message', handler);
                        const info = msg.act_id === 1000 && msg.code === 0 ? msg.data : msg;
                        this.characterInfo = {
                            id: info.id,
                            name: info.name,
                            lvl: info.lvl,
                            exp: info.exp,
                        };
                        console.log('✅ 角色信息:', JSON.stringify({
                            id: this.characterInfo.id,
                            name: this.characterInfo.name,
                            lvl: this.characterInfo.lvl,
                            exp: this.characterInfo.exp
                        }));
                        this.addTestResult('查询角色信息', true, `等级=${this.characterInfo.lvl}, 经验=${this.characterInfo.exp}`);
                        return resolve();
                    }
                } catch (_) { }
            };
            this.ws.on('message', handler);
            this.ws.send(JSON.stringify({ c: 1000, d: null }));
        });
    }

    async testContinuousTraining() {
        console.log('\n🏋️ 步骤7: 持续训练测试...');
        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            this.addTestResult('持续训练测试', false, 'WebSocket未连接');
            return;
        }

        // 先确认训练详情(1205)并处理待领取(1208)，然后动态规划训练时长
        await this.ensureReadyForTraining();

        // 领取后刷新一次角色信息作为新的基准
        const refreshed = await this.queryCharacterInfoAfterTraining();
        if (refreshed) {
            this.characterInfo = refreshed;
        }

        let trainingCount = 0;
        const maxTraining = 50; // 最多训练50次
        let currentLevel = this.characterInfo?.lvl || 1;
        let currentExp = this.characterInfo?.exp || 0;

        console.log(`🎯 开始训练，当前等级: ${currentLevel}, 当前经验: ${currentExp}`);

        while (trainingCount < maxTraining) {
            trainingCount++;
            console.log(`\n📝 第${trainingCount}次训练...`);

            // 动态计算本次训练小时数（基于1205返回的金币与单价）
            const plan = await this.getTrainingPlanFrom1205();
            const hours = plan.affordableHours > 0 ? Math.min(10, plan.affordableHours) : 1;
            const previousLevel = currentLevel;
            const trainingResult = await this.performSingleTraining(hours);
            if (!trainingResult.success) {
                console.log(`❌ 第${trainingCount}次训练失败: ${trainingResult.message}`);
                this.addTestResult(`训练${trainingCount}`, false, trainingResult.message);
                break;
            }

            console.log(`✅ 第${trainingCount}次训练成功: ${trainingResult.message}`);
            this.addTestResult(`训练${trainingCount}`, true, trainingResult.message);

            // 训练成功后，若1205为可领取(k=3)，自动发送1208领取
            const postPlan = await this.getTrainingPlanFrom1205();
            if (postPlan.canClaim) {
                await this.claimTrainingReward();
                // 领取后短暂等待再刷新
                await this.delay(300);
            }

            // 查询角色信息检查是否升级
            await this.delay(1000);
            const newCharacterInfo = await this.queryCharacterInfoAfterTraining();
            if (newCharacterInfo) {
                const newLevel = newCharacterInfo.lvl;
                const newExp = newCharacterInfo.exp;

                console.log(`📊 训练后状态: 等级=${newLevel}, 经验=${newExp}`);

                if (newLevel > currentLevel) {
                    console.log(`🎉 角色升级了！从等级${currentLevel}升级到等级${newLevel}`);
                    this.addTestResult('角色升级', true, `从等级${currentLevel}升级到等级${newLevel}`);

                    // 验证升级后的状态
                    await this.validateLevelUpState(previousLevel, newLevel, newExp);
                    break;
                }

                // 检查经验是否正确减少
                if (newExp < currentExp) {
                    console.log(`✅ 经验正确减少: ${currentExp} → ${newExp}`);
                } else if (newExp > currentExp) {
                    console.log(`❌ 经验错误增加: ${currentExp} → ${newExp}`);
                    this.addTestResult('经验计算', false, `经验应该减少但增加了: ${currentExp} → ${newExp}`);
                }

                currentLevel = newLevel;
                currentExp = newExp;
            }

            await this.delay(2000); // 等待2秒再进行下一次训练
        }

        if (trainingCount >= maxTraining) {
            console.log(`⚠️ 达到最大训练次数${maxTraining}，未检测到升级`);
            this.addTestResult('持续训练测试', false, `训练${maxTraining}次未升级`);
        }
    }

    async performSingleTraining(hours = 1) {
        return new Promise((resolve) => {
            let responseReceived = false;

            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 1207) {
                        this.ws.removeListener('message', responseHandler);
                        clearTimeout(timeoutId);
                        responseReceived = true;

                        this.trainingResults.push({
                            act_id: message.act_id,
                            code: message.code,
                            msg: message.msg,
                            timestamp: new Date().toISOString()
                        });

                        if (message.code === 0) {
                            resolve({ success: true, message: message.msg });
                        } else {
                            resolve({ success: false, message: message.msg || '训练失败' });
                        }
                    }
                } catch (error) {
                    this.ws.removeListener('message', responseHandler);
                    clearTimeout(timeoutId);
                    resolve({ success: false, message: '响应解析失败' });
                }
            };

            this.ws.on('message', responseHandler);
            this.ws.send(JSON.stringify({
                c: 1207,
                d: { h: hours } // 动态训练小时
            }));

            const timeoutId = setTimeout(() => {
                if (!responseReceived) {
                    this.ws.removeListener('message', responseHandler);
                    resolve({ success: false, message: '请求超时' });
                }
            }, 15000);
        });
    }

    async queryCharacterInfoAfterTraining() {
        return new Promise((resolve) => {
            const timeout = setTimeout(() => {
                this.ws.removeListener('message', handler);
                resolve(null);
            }, 5000);

            const handler = (raw) => {
                try {
                    const msg = JSON.parse(raw.toString());
                    if (msg && (msg.act_id === 1000 || msg.act_id === 300)) {
                        clearTimeout(timeout);
                        this.ws.removeListener('message', handler);
                        const info = msg.act_id === 1000 && msg.code === 0 ? msg.data : msg;
                        resolve(info);
                    }
                } catch (_) { }
            };
            this.ws.on('message', handler);
            this.ws.send(JSON.stringify({ c: 1000, d: null }));
        });
    }

    async ensureReadyForTraining() {
        // 循环检查1205状态，若可领取则先领取(1208)，若训练中则等待
        for (let i = 0; i < 5; i++) {
            const plan = await this.getTrainingPlanFrom1205();
            if (plan.canClaim) {
                await this.claimTrainingReward();
                await this.delay(500);
                continue;
            }
            if (plan.isTraining) {
                await this.delay(1000);
                continue;
            }
            break;
        }
        await this.delay(300);
    }

    async getTrainingPlanFrom1205() {
        return new Promise((resolve) => {
            let timeoutId;
            const handler = (raw) => {
                try {
                    const msg = JSON.parse(raw.toString());
                    if (msg && msg.act_id === 1205) {
                        this.ws.removeListener('message', handler);
                        clearTimeout(timeoutId);
                        let k = msg.data?.k || '0';
                        let v = msg.data?.v || '';
                        const goldMatch = typeof v === 'string' ? v.match(/有(\d+)金/) : null;
                        const costMatch = typeof v === 'string' ? v.match(/每小时(\d+)金/) : null;
                        const gold = goldMatch ? parseInt(goldMatch[1], 10) : 0;
                        const cost = costMatch ? parseInt(costMatch[1], 10) : 0;
                        const affordableHours = cost > 0 ? Math.floor(gold / cost) : 1;
                        resolve({
                            statusKey: k,
                            isTraining: k === '1',
                            canClaim: k === '3',
                            affordableHours: isFinite(affordableHours) ? affordableHours : 1,
                        });
                    }
                } catch (_) { }
            };
            this.ws.on('message', handler);
            this.ws.send(JSON.stringify({ c: 1205, d: null }));
            timeoutId = setTimeout(() => {
                this.ws.removeListener('message', handler);
                resolve({ statusKey: 'timeout', isTraining: false, canClaim: false, affordableHours: 1 });
            }, 5000);
        });
    }

    async claimTrainingReward() {
        return new Promise((resolve) => {
            let timeoutId;
            const handler = (raw) => {
                try {
                    const msg = JSON.parse(raw.toString());
                    if (msg && msg.act_id === 1208) {
                        this.ws.removeListener('message', handler);
                        clearTimeout(timeoutId);
                        if (msg.code === 0) {
                            console.log('🎁 已领取训练奖励');
                        } else {
                            console.log(`⚠️ 领取训练奖励失败: ${msg.msg || '未知错误'}`);
                        }
                        resolve();
                    }
                } catch (_) { }
            };
            this.ws.on('message', handler);
            this.ws.send(JSON.stringify({ c: 1208, d: null }));
            timeoutId = setTimeout(() => {
                this.ws.removeListener('message', handler);
                resolve();
            }, 5000);
        });
    }

    async validateLevelUpState(prevLevel, newLevel, newExp) {
        console.log('\n🔍 验证升级后状态...');

        // 检查经验是否重置为下一级所需经验；达到上限(100级且未转)时允许为0
        const reachedCap = newLevel >= 100; // 未转上限为100
        if (reachedCap && newExp === 0) {
            console.log(`✅ 达到等级上限，升级后经验为0是预期行为`);
            this.addTestResult('升级后经验重置', true, '达到上限经验为0');
        } else if (newExp > 0) {
            console.log(`✅ 升级后经验重置为: ${newExp} (下一级所需经验)`);
            this.addTestResult('升级后经验重置', true, `经验重置为${newExp}`);
        } else {
            console.log(`❌ 升级后经验为0，可能有问题`);
            this.addTestResult('升级后经验重置', false, '升级后经验为0');
        }

        // 检查等级是否正确提升
        if (newLevel > prevLevel) {
            console.log(`✅ 等级正确提升: ${prevLevel} → ${newLevel}`);
            this.addTestResult('等级提升验证', true, `等级从${prevLevel}提升到${newLevel}`);
        } else {
            console.log(`❌ 等级未正确提升`);
            this.addTestResult('等级提升验证', false, '等级未正确提升');
        }
    }

    async testHttpLogin() {
        console.log('🔐 步骤1: HTTP登录测试...');
        try {
            await this.registerUser();
            const loginData = await this.makeHttpRequest('/user-service/user/login', 'POST', {
                mobile: CONFIG.testUser.mobile,
                pwd: CONFIG.testUser.passwordHash
            });

            if (loginData.code === 0 && loginData.data) {
                this.userId = loginData.data.userId;
                this.token = loginData.data.accessToken;
                console.log(`✅ 登录成功: userId=${this.userId}`);
                this.addTestResult('HTTP登录', true, `用户ID: ${this.userId}`);
            } else {
                throw new Error(`登录失败: ${loginData.msg || '未知错误'}`);
            }
        } catch (error) {
            console.log('❌ 登录失败:', error.message);
            this.addTestResult('HTTP登录', false, error.message);
            throw error;
        }
    }

    async registerUser() {
        try {
            const res = await this.makeHttpRequest('/user-service/user/register', 'POST', {
                mobile: CONFIG.testUser.mobile,
                pwd: CONFIG.testUser.passwordHash,
                captcha: '123456'
            });
            console.log('📝 用户注册成功', res);
        } catch (error) {
            if (error.message.includes('MOBILE_EXISTS') || error.message.includes('已存在')) {
                console.log('👤 用户已存在，跳过注册');
            } else {
                console.log('⚠️ 注册失败:', error.message);
            }
        }
    }

    async testWebSocketConnection() {
        console.log('\n🔌 步骤2: WebSocket连接测试...');
        return new Promise((resolve, reject) => {
            try {
                const wsUrl = `ws://127.0.0.1:${CONFIG.server.port}/user-service/websocket?t=${this.token}`;
                this.ws = new WebSocket(wsUrl);

                this.ws.on('open', async () => {
                    console.log('✅ WebSocket连接成功');
                    this.addTestResult('WebSocket连接', true, '连接建立成功');
                    this.setupMessageHandler();
                    await this.delay(500);
                    resolve();
                });

                this.ws.on('error', (error) => {
                    console.log('❌ WebSocket连接失败:', error.message);
                    this.addTestResult('WebSocket连接', false, error.message);
                    reject(error);
                });

                this.ws.on('close', () => {
                    console.log('🔌 WebSocket连接已关闭');
                });

                setTimeout(() => {
                    if (this.ws.readyState === WebSocket.CONNECTING) {
                        this.ws.close();
                        reject(new Error('连接超时'));
                    }
                }, 10000);
            } catch (error) {
                reject(error);
            }
        });
    }

    setupMessageHandler() {
        this.ws.on('message', (data) => {
            try {
                const message = JSON.parse(data.toString());
                console.log('📨 收到消息:', JSON.stringify(message, null, 2));
                this.handleWebSocketResponse(message);
            } catch (error) {
                console.error('❌ 消息解析失败:', error.message);
            }
        });
    }

    handleWebSocketResponse(message) {
        const { act_id, code, roleList, roleCount, data, msg } = message;

        switch (act_id) {
            case 3:
                if (roleList && Array.isArray(roleList)) {
                    this.characters = roleList;
                    console.log(`📋 获取到${roleCount || roleList.length}个角色`);
                }
                break;
            case 4:
                if (code === 0) {
                    console.log('🎯 角色选择成功');
                }
                break;
            case 5:
            case 390:
                if (code === 0) {
                    console.log('🆕 角色创建成功');
                }
                break;
            case 1000:
                if (code === 0) {
                    this.characterInfo = data;
                    console.log(`👤 角色信息更新: 等级=${data.lvl}, 经验=${data.exp}`);
                }
                break;
            case 300:
                this.characterInfo = {
                    id: message.id,
                    name: message.name,
                    lvl: message.lvl,
                    exp: message.exp,
                };
                if (this.characterInfo && this.characterInfo.id) {
                    console.log(`👤 角色信息快照: 等级=${this.characterInfo.lvl}, 经验=${this.characterInfo.exp}`);
                }
                break;
            case 1207:
                console.log(`🏋️ 训练结果: ${msg}`);
                break;
        }
    }

    async testQueryCharacters() {
        console.log('\n📋 步骤3: 查询角色列表...');
        return new Promise(async (resolve) => {
            if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
                this.addTestResult('查询角色列表', false, 'WebSocket未连接');
                resolve();
                return;
            }

            await this.delay(1000);

            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 3) {
                        this.ws.removeListener('message', responseHandler);
                        clearTimeout(timeoutId);

                        if (message.roleList && Array.isArray(message.roleList)) {
                            this.characters = message.roleList;
                            console.log(`✅ 查询成功，共${message.roleCount || message.roleList.length}个角色`);
                            this.addTestResult('查询角色列表', true, `获取${this.characters.length}个角色`);
                        } else {
                            this.characters = [];
                            console.log('✅ 查询成功，暂无角色');
                            this.addTestResult('查询角色列表', true, '获取0个角色');
                        }
                        resolve();
                    }
                } catch (error) {
                    this.ws.removeListener('message', responseHandler);
                    clearTimeout(timeoutId);
                    this.addTestResult('查询角色列表', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);
            this.ws.send(JSON.stringify({ c: 3, d: null }));

            const timeoutId = setTimeout(() => {
                this.ws.removeListener('message', responseHandler);
                this.addTestResult('查询角色列表', false, '请求超时');
                resolve();
            }, 10000);
        });
    }

    async testCreateCharacter() {
        console.log('\n🆕 步骤4: 创建角色测试...');
        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            this.addTestResult('创建角色', false, 'WebSocket未连接');
            return;
        }

        return new Promise((resolve) => {
            let responseReceived = false;
            let retryCount = 0;
            const maxRetries = 2;

            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 5 || message.act_id === 390) {
                        this.ws.removeListener('message', responseHandler);
                        responseReceived = true;

                        if (message.code === 0) {
                            console.log('✅ 角色创建成功');
                            this.addTestResult('创建角色', true, '角色创建成功');
                            setTimeout(() => resolve(), 2000);
                        } else {
                            const errorMsg = message.msg || '未知错误';
                            console.log(`❌ 角色创建失败: ${errorMsg}`);

                            if (errorMsg.includes('重复') || errorMsg.includes('已存在') || errorMsg.includes('DUPLICATE')) {
                                if (retryCount < maxRetries) {
                                    retryCount++;
                                    const newName = `${CONFIG.testCharacter.name}_${Date.now()}`;
                                    console.log(`🔄 角色名重复，尝试使用新名字: ${newName}`);
                                    setTimeout(() => {
                                        this.createCharacterWithName(newName, resolve);
                                    }, 1000);
                                    return;
                                }
                            }

                            this.addTestResult('创建角色', false, errorMsg);
                            resolve();
                        }
                    }
                } catch (error) {
                    console.error('❌ 创建角色响应解析失败:', error.message);
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('创建角色', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);
            this.createCharacterWithName(CONFIG.testCharacter.name, resolve);

            setTimeout(() => {
                if (!responseReceived) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('创建角色', false, '请求超时');
                    resolve();
                }
            }, 15000);
        });
    }

    createCharacterWithName(name, resolve) {
        const createData = {
            c: 5,
            d: {
                name: name,
                sex: CONFIG.testCharacter.sex,
                roleType: CONFIG.testCharacter.roleType,
                headIndex: CONFIG.testCharacter.headIndex
            }
        };

        console.log(`📤 发送创建角色请求:`, JSON.stringify(createData, null, 2));
        this.ws.send(JSON.stringify(createData));
    }

    async testSelectCharacter() {
        console.log('\n🎯 步骤5: 选择角色...');
        if (this.characters.length === 0) {
            console.log('⚠️ 没有可选择的角色');
            this.addTestResult('选择角色', false, '没有可用角色');
            return;
        }

        return new Promise((resolve) => {
            if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
                this.addTestResult('选择角色', false, 'WebSocket未连接');
                resolve();
                return;
            }

            // 选择等级较低的角色进行测试
            const targetCharacter = this.characters.find(char => char.lvl <= 5) || this.characters[0];
            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 4) {
                        this.ws.removeListener('message', responseHandler);
                        clearTimeout(timeoutId);

                        if (message.code === 0) {
                            this.selectedCharacter = targetCharacter;
                            console.log(`✅ 角色选择成功: ${targetCharacter.name} (ID: ${targetCharacter.id})`);
                            this.addTestResult('选择角色', true, `选择角色: ${targetCharacter.name}`);
                            setTimeout(() => resolve(), 2000);
                        } else {
                            console.log(`❌ 角色选择失败: ${message.msg || '未知错误'}`);
                            this.addTestResult('选择角色', false, message.msg || '选择失败');
                            resolve();
                        }
                    }
                } catch (error) {
                    this.ws.removeListener('message', responseHandler);
                    clearTimeout(timeoutId);
                    this.addTestResult('选择角色', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);
            this.ws.send(JSON.stringify({
                c: 4,
                d: { characterId: targetCharacter.id }
            }));

            const timeoutId = setTimeout(() => {
                this.ws.removeListener('message', responseHandler);
                this.addTestResult('选择角色', false, '请求超时');
                resolve();
            }, 10000);
        });
    }

    async testDisconnect() {
        console.log('\n🔌 步骤8: 断开WebSocket连接...');
        if (this.ws) {
            this.ws.close();
        }
        this.addTestResult('断开连接', true, '连接已断开');
    }

    addTestResult(testName, success, message) {
        this.testResults.push({
            test: testName,
            success: success,
            message: message,
            timestamp: new Date().toISOString()
        });
    }

    printTestResults() {
        console.log('\n📊 测试结果汇总:');
        console.log('='.repeat(50));

        let successCount = 0;
        let totalCount = this.testResults.length;

        this.testResults.forEach((result, index) => {
            const status = result.success ? '✅' : '❌';
            console.log(`${index + 1}. ${status} ${result.test}: ${result.message}`);
            if (result.success) successCount++;
        });

        console.log('='.repeat(50));
        console.log(`总计: ${successCount}/${totalCount} 项测试通过`);

        if (successCount === totalCount) {
            console.log('🎉 所有测试通过！1207接口训练功能正常！');
        } else {
            console.log('⚠️  部分测试失败，请检查日志');
        }

        if (this.trainingResults && this.trainingResults.length > 0) {
            console.log('\n🏋️ 训练结果分析:');
            console.log('='.repeat(50));
            console.log(`总训练次数: ${this.trainingResults.length}`);

            const successTrainings = this.trainingResults.filter(r => r.code === 0);
            const failedTrainings = this.trainingResults.filter(r => r.code !== 0);

            console.log(`成功训练: ${successTrainings.length}次`);
            console.log(`失败训练: ${failedTrainings.length}次`);

            if (successTrainings.length > 0) {
                console.log('\n✅ 成功训练详情:');
                successTrainings.forEach((training, index) => {
                    console.log(`  ${index + 1}. ${training.msg} (${training.timestamp})`);
                });
            }

            if (failedTrainings.length > 0) {
                console.log('\n❌ 失败训练详情:');
                failedTrainings.forEach((training, index) => {
                    console.log(`  ${index + 1}. ${training.msg} (${training.timestamp})`);
                });
            }
        }
    }

    async makeHttpRequest(path, method = 'GET', data = null) {
        return new Promise((resolve, reject) => {
            const options = {
                hostname: CONFIG.server.host,
                port: CONFIG.server.port,
                path: path,
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                }
            };

            if (data) {
                const postData = JSON.stringify(data);
                options.headers['Content-Length'] = Buffer.byteLength(postData);
            }

            const req = http.request(options, res => {
                let body = '';
                res.on('data', (chunk) => { body += chunk; });
                res.on('end', () => {
                    try {
                        const responseData = JSON.parse(body);
                        if (res.statusCode >= 200 && res.statusCode < 300) {
                            resolve(responseData);
                        } else {
                            reject(new Error(`HTTP ${res.statusCode}: ${responseData.message || body}`));
                        }
                    } catch (error) {
                        if (res.statusCode >= 200 && res.statusCode < 300) {
                            resolve(body);
                        } else {
                            reject(new Error(`HTTP ${res.statusCode}: ${body}`));
                        }
                    }
                });
            });

            req.on('error', (error) => { reject(error); });
            if (data) { req.write(JSON.stringify(data)); }
            req.end();
        });
    }

    async delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}

async function main() {
    const tester = new Code1207Tester();
    await tester.runTest();
}

if (require.main === module) {
    main().catch((error) => {
        console.error('💥 测试脚本执行失败:', error.message);
        process.exit(1);
    });
}

module.exports = Code1207Tester;
